<?php
/**
 * 快找设计师专题控制器
 */
namespace Beerus\Modules\DesignerFinder\Controllers;

use App\Http\Controllers\Controller;
use Beerus\Modules\DesignerFinder\Actions\Offline;
use Beerus\Modules\DesignerFinder\Actions\Online;
use Common\Lib\Hhzurl;
use Doraemon\model\Article;
use Doraemon\model\DesignerFinder\Subject;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid\Displayers\DropdownActions;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use App\Pockets\GridDataModel as pGridDataModel;
use Encore\Admin\Widgets\Tab;
use Illuminate\Support\MessageBag;

class SubjectController extends Controller
{

    const PAGE_SIZE = 10;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    // 对话列表
    public function index(Request $request, Content $content)
    {
        $page_size = $request->input("per_page", self::PAGE_SIZE);
        $page = $request->input("page", 1);

        $condition = [];
        if (!empty($request['id'])) {
            $condition['id'] = $request['id'];
        }

        $condition['data_status[<]'] = Subject::STATUS_DELETE;
        $total = Subject::count($condition);
        $condition['ORDER'] = ['id' => 'DESC'];
        $condition['LIMIT'] = [
            ($page - 1) * $page_size,
            $page_size
        ];
        $lists = Subject::select('*', $condition);
        foreach ($lists as &$item) {
            $item['subject_link'] = "/pages/subject/index?subject_id={$item['id']}";
        }

        $gridModel = new pGridDataModel($lists, $total, [
            'perPage' => $page_size
        ]);

        $search_params = http_build_query($condition);
        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel, $search_params) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();

                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('id', '专题ID')->placeholder('请输入专题ID');
                    });
                    $filter->expand();
                });

                $grid->column('id', '专题ID');
                $grid->column('subject_title', '专题名称');
                $grid->column('add_time', '创建时间')->display(function () {
                    return date('Y-m-d H:i:s', $this->add_time);
                });
                $grid->column('remark', '备注');
                $grid->column('subject_link', '专题链接')->display(function () {})->copyable();
                $grid->column('qr_code', '私域微信二维码')->display(function () {
                    if (!empty($this->qr_code)) {
                        $sQrCodeUrl = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $this->qr_code, ImgUrl::IMAGE_SIZE_O_500);
                        $sImgHtml = '<img height=500 src='.$sQrCodeUrl.' />';
                        $sHtml = '<a class="fa " href="javascript:layer.open(
                        {
                            type: 1,
                            title: false, 
                            maxmin: true, 
                            area: [\'auto\', \'auto\'],
                            fixed: false,
                            offset: \'auto\',
                            content: \''.$sImgHtml.'\'
                        });">查看</a>';
                    } else {
                        $sHtml = '未配置';
                    }
                    return $sHtml;
                });
                $grid->column('data_status', '状态')->using([
                    1 => '已下线',
                    2 => '已上线',
                ], '未知')->dot([
                    1 => 'danger',
                    2 => 'info',
                ], 'warning');;

                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                    $actions->disableView();
                    $actions->disableEdit();
                    $actions->append("<a class='btn btn-xs action-btn btn-info grid-row-edit' href=\"/admin/DesignerFinder/subject/".$this->row['id']."/edit\" class=\"btn btn-primary\">编辑</a>&nbsp;&nbsp;");
                    if ($this->row['data_status'] == Subject::STATUS_OFFLINE) {
                        $actions->append("<a class='btn btn-xs action-btn btn-success grid-row-online' data-id='{$actions->getKey()}' data-banner='{$this->row['subject_banner_id']}'><i class='fa fa-check' title='同意退款'>上线</i></a>&nbsp;&nbsp;");
                    }
                    if ($this->row['data_status'] == Subject::STATUS_ONLINE) {
                        $actions->append("<a class='btn btn-xs action-btn btn-danger grid-row-offline' data-id='{$actions->getKey()}'><i class='fa fa-close' title='拒绝退款'>下线</i></a>");
                    }
                });
                Admin::script($this->setIndexScript());
            }
        );

        $tab = new Tab();
        $tab->add('专题管理列表', $gridList->render());
        $content->row($tab);
        return $content
            ->header('专题页管理')
            ->description(' ')
            ->breadcrumb(['text' => '专题管理列表']);
    }

    public function edit(Request $request, Content $content, $id = 0) {
        Admin::script($this->setScript());
        $request = $request->all();
        if (!$id) {
            $isCreate = true;
            $header = '新增';
        } else {
            $isCreate = false;
            $header = '修改';
        }
        if ($isCreate) {
            $data = [];
            $form = new Form($data);
        } else {
            $data = Subject::get('*', ['id' => $id]);
            $aDesignerList = json_decode($data['designer_list'], true);
            if (!empty($aDesignerList)) {
                foreach ($aDesignerList as $iKey => $aDesignerItem) {
                    if ($aDesignerItem['_remove_'] == 1) {
                        unset($aDesignerList[$iKey]);
                    }
                }
            }
            $data['designer_list'] = $aDesignerList;
            $form = new Form($data);
            $form->text('id', '专题ID')->readOnly();
        }

        $form->text('subject_title', '专题名称')->required('不能为空')->help("最长不超过15个字");
        $form->imgUpload('subject_cover_id', '封面图')->help('单图，必须上传');
        $form->imgUpload('subject_banner_id', 'banner图')
            ->setMinImageHeight(270)
            ->setMaxImageHeight(270)
            ->setMinImageWight(1029)
            ->setMaxImageWight(1029)
            ->help('请务必上传1029（宽） x 270（高）尺寸的图片，尺寸不合规，会提示Bad Request!!!');
        $form->text('remark', '备注');
        $form->table('designer_list', '设计师列表', function ($table) use ($data) {
            $table->text('designer_uid', '设计师uid');
            $table->text('assoc_article', '关联案例')->help('以英文逗号分隔，例如：1,2,3；最多3个案例，最少1个');
        });
        $form->imgUpload('qr_code', '私域微信二维码', false, ['imgType' => ImgUrl::APPTYPE_OP, 'imgSize' => ImgUrl::IMAGE_SIZE_O_500])->help('单图，必须上传');
        $form->disablePjax();

        $tab = new Tab();
        $tab->add('专题信息', $form->render());
        return $content->header($header)
            ->breadcrumb([
                'text' => '专题列表',
                'url' => route('subject.list')
            ], ['text' => $header])->row($tab);
    }

    public function save(Request $request) {
        $request = $request->all();
        if (($ret = self::checkRequest($request)) !== true) {
            return response()->json([
                'status' => false,
                'message' => $ret
            ]);
        }
        $designerList = array_values($request['designer_list']);
        array_walk($designerList, function (&$item) {
            $item['assoc_article'] = str_replace(' ', '', $item['assoc_article']);
        });
        $designerList = array_filter($designerList, function ($aItem) {
            return $aItem['_remove_']==0;
        });
        $data = [
            'subject_title' => $request['subject_title'],
            'subject_cover_id' => $request['subject_cover_id'],
            'subject_banner_id' => $request['subject_banner_id'],
            'remark' => $request['remark'],
            'designer_list' => json_encode($designerList),
            'qr_code' => $request['qr_code'],
            'admin_id' => Admin::user()->id
        ];
        if (!empty($request['id'])) {
            $rs = Subject::updateInfo($data, ['id' => $request['id']]);
        } else {
            $rs = Subject::addInfo($data);
        }
        $title = !empty($request['id']) ? '修改' : '添加';
        if (!$rs) {
            return response()->json([
                'status' => false,
                'message' => "专题{$title}失败"
            ]);
        }
        return response()->json([
            'status' => true,
            'message' => "专题{$title}成功"
        ]);
    }

    public static function checkRequest($aRequestParams) {
        $subjectTitle = $aRequestParams['subject_title'];
        $subjectCoverId = $aRequestParams['subject_cover_id'];
        $designerList = $aRequestParams['designer_list'];
        $qrCode = $aRequestParams['qr_code'];
        if (empty($subjectTitle)) {
            return '专题名称不可为空';
        }
        if (mb_strlen($subjectTitle) > 15) {
            return '专题名称不可超过15个字';
        }
        if (empty($subjectCoverId)) {
            return '专题封面图不可为空';
        }
        if (empty($designerList)) {
            return '设计师列表不可为空1';
        }
        if (empty($qrCode)) {
            return '私域微信二维码不可为空';
        }
        if (count($designerList) > 20) {
            return '最多配置20个设计师';
        }
        foreach ($designerList as $designerItem) {
            if (empty($designerItem['designer_uid'])) {
                return '设计师列表不可为空2';
            }
            if (!\Doraemon\model\Designer::getInfo($designerItem['designer_uid'])) {
                return "设计师「{$designerItem['designer_uid']}」不存在";
            }
            if (empty($designerItem['assoc_article'])) {
                return "设计师「{$designerItem['designer_uid']}」的关联整屋id不可为空";
            }
            $assocArticleList = explode(',', $designerItem['assoc_article']);
            if (count($assocArticleList) > 3) {
                return "设计师「{$designerItem['designer_uid']}」最多关联3个整屋";
            }
            foreach ($assocArticleList as $articleId) {
                if (!Article::get('*', ['uid' => $designerItem['designer_uid'], 'aid' => trim($articleId)])) {
                    return "整屋「{$articleId}」不存在，或不属于设计师「{$designerItem['designer_uid']}」";
                }
            }
        }
        return true;
    }

    public function online(Request $request, Content $content, $iSubjectId = 0) {
        $aSubjectInfo = Subject::getSubjectInfoById($iSubjectId);
        if (empty($aSubjectInfo['qr_code'])) {
            return response()->json([
                'status' => false,
                'message' => '私域微信二维码未配置'
            ]);
        }
        if (($cnt = Subject::countOnlineSubject()) >= 3) {
            return response()->json([
                'status' => false,
                'message' => '仅允许上线'.$cnt.'个专题'
            ]);
        }
        if (!Subject::onlineSubject($iSubjectId)) {
            return response()->json([
                'status' => false,
                'message' => '上线失败'
            ]);
        }
        return response()->json([
            'status' => true,
            'message' => '上线成功'
        ]);
    }

    public function offline(Request $request, Content $content, $iSubjectId = 0) {
        if (!Subject::offlineSubject($iSubjectId)) {
            return response()->json([
                'status' => false,
                'message' => '下线失败'
            ]);
        }
        return response()->json([
            'status' => true,
            'message' => '下线成功'
        ]);
    }

    /*设置scirpt
    *
    * */
    private function setScript() {
        return <<<SCRIPT
            $(':submit').click(function(e){
                // 判断专题数据是否正常
                var designerList = new Array();
                $(".has-many-designer_list-form:visible").each(function(key,val) {
                    designerList.push({
                        designer_uid: $(this).find('#designer_uid').val(),
                        assoc_article: $(this).find('#assoc_article').val()
                    });
                });
                let url = '/admin/DesignerFinder/subject/save';
                let params = {
                    id: $('#id').val(),
                    subject_title:$('#subject_title').val(),
                    subject_cover_id:$("input[name='subject_cover_id']").val(),
                    subject_banner_id:$("input[name='subject_banner_id']").val(),
                    remark:$('#remark').val(),
                    designer_list:designerList,
                    qr_code:$("input[name='qr_code']").val(),
                };
                $.ajaxSetup({
                    async : false
                });
                $.post(url, params, function (result) {
                    console.log(result)
                    layer.msg(result.message);
                    if (result.status == false) {
                        return false;
                    } else {
                        setTimeout(function () {
                            window.location.href = "/admin/DesignerFinder/subject";
                        }, 1000);
                    }
                });
            })
        SCRIPT;
    }

    /**
     * 列表脚本
     */
    private function setIndexScript() {
        return <<<SCRIPT
            $('.grid-row-online').unbind('click').click(function() {
                var id = $(this).data('id');
                var banner = $(this).data('banner');
                var confirmTxt = '';
                if (banner == '') {
                    confirmTxt = '您还未配置banner图，是否仍要继续上线?';
                } else {
                    confirmTxt = '确定上线？';
                }
                swal({
                    title: confirmTxt,
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "确认",
                    showLoaderOnConfirm: true,
                    cancelButtonText: "取消",
                    preConfirm: function() {
                        $.ajax({
                            method: 'get',
                            url: '/admin/DesignerFinder/subject/online/' + id, 
                            success: function (data) {
                                $.pjax.reload('#pjax-container');
                                if(data.status){
                                    swal(data.msg, '', 'success');
                                }else{
                                    swal(data.msg, '', 'error');
                                }
                            }
                        });
                    }
                });
            });
            
            $('.grid-row-offline').unbind('click').click(function() {
                var id = $(this).data('id');
                swal({
                    title: "确定下线该专题？",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "确认",
                    showLoaderOnConfirm: true,
                    cancelButtonText: "取消",
                    preConfirm: function() {
                        $.ajax({
                            method: 'get',
                            url: '/admin/DesignerFinder/subject/offline/' + id, 
                            success: function (data) {
                                console.log(data);
                                $.pjax.reload('#pjax-container');
                                if(data.status){
                                    swal(data.msg, '', 'success');
                                }else{
                                    swal(data.msg, '', 'error');
                                }
                            }
                        });
                    }
                });
            });
        SCRIPT;
    }
}
